/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.mqtt.broker.impl.request

import cool.taomu.software.fig.classloader.FigClassLoaderManage.Autowired
import cool.taomu.software.fig.mqtt.broker.MQTTCache
import cool.taomu.software.fig.mqtt.broker.entity.MessageEntity
import cool.taomu.software.fig.mqtt.broker.entity.PubRelEntity
import cool.taomu.software.fig.mqtt.broker.inter.IRequest
import cool.taomu.software.fig.mqtt.broker.inter.IResponse
import cool.taomu.software.fig.mqtt.utils.CommonUtils
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.mqtt.MqttMessage
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader
import org.slf4j.LoggerFactory

/**
 * PUBREL |	6 	|	两个方向都允许 	|	发布释放(保证交付第二步)
 */
class MQTTPubRel implements IRequest {
	val LOG = LoggerFactory.getLogger(MQTTPubRel);

	@Autowired(cool.taomu.software.fig.mqtt.broker.impl.response.MQTTPubRel)
	IResponse<PubRelEntity> pubRel;

	MQTTCache cache2 = MQTTCache.instance

	override request(ChannelHandlerContext ctx, MqttMessage mqttMessage) {
		var clientId = CommonUtils.getClientId(ctx.channel);
		LOG.info("执行了MQTT PubRel 命令 : " + clientId);
		// TODO 需要添加判断clientId
		var idVariableHeader = mqttMessage.variableHeader as MqttMessageIdVariableHeader;
		var msgId = idVariableHeader.messageId();
		// 回给订阅者这个一个REL命令
		var qos2 = cache2.loadQoS2Message(clientId);
		for (q : qos2) {
			var msg = q as MessageEntity;
			var entity = pubRel.response(new PubRelEntity(msgId));
			msg.senderChannel.writeAndFlush(entity);
			if (cache2.clearQoS2Message(clientId, msg)) {
				LOG.info("clear QoS2 message success.");
			}
			msg.senderChannel = ctx.channel;
			var senderId = msg.senderId;
			msg.senderId = clientId;
			cache2.storeQoS2Message(senderId, msg);
		}
		return null; // #[response.response(new PubCompEntity(msgId))];
	}

}
